package cn.wolfcode.luowowo.webSite.param;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.webSite.annotation.UserParam;
import cn.wolfcode.luowowo.webSite.util.CookieUtil;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

//请求映射方法注入自定义请求参数
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //支持解析参数类型
        //只有return true, 才执行下面解析方法resolveArgument

        //使用注解原因: 让springmvc 使用自定义参数注入方案
        return methodParameter.hasParameterAnnotation(UserParam.class)
                && methodParameter.getParameterType() == UserInfo.class;
    }

    //这个方法返回值, 会注入到请求映射方法中,形式参数类型为UserInfo 这个对象了里面
    /**
     * userinfo = resolveArgument(...)
     * 执行resolveArgument 完之后, 将参数注入到 userInfo方法中 UserInfo 形式参数中
     *
     *  public Object userInfo(HttpServletRequest request, UserInfo userInfo){...}
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取请求对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getToken(request);
        UserInfo userInfo = null;
        if(token != null){
            //从redis中获取token 对应用户对象
            userInfo = userInfoRedisService.getUserByToken(token);
            System.out.println(1);
        }
        return userInfo;
    }
}